package com.piece.member.service;

import com.piece.admin.model.TbSysUser;
import com.piece.core.framework.util.collection.CollectionUtil;
import com.piece.core.framework.util.collection.MapUtil;
import com.piece.core.framework.util.object.BeanUtil;
import com.piece.member.model.UmsMember;
import com.piece.member.repository.UmsMemberRepository;
import com.piece.core.jpa.repository.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class UmsMemberService extends BaseService<UmsMember, String> {

    @Autowired
    private UmsMemberRepository umsMemberRepository;

    @PostConstruct
    public void initRepository() {
        setRepository(umsMemberRepository);
    }

    public UmsMember findByUser(Long userId) {
        List<UmsMember> members = umsMemberRepository.findByCondition("select m.*, l.name as levelName from `ums_member` m left join `ums_member_level` l " +
                "on m.level_id = l.id ", "m", MapUtil.builder(new HashMap<String, Object>())
                .put("userId", userId)
                .build(), null);
        return CollectionUtil.isNotEmpty(members) ? members.get(0) : null;
    }

    public void bindByUser(TbSysUser user) {
        UmsMember umsMember = umsMemberRepository.findOneByCondition( MapUtil.builder(new HashMap<String, Object>())
                .put("userId", user.getUserId())
                .build());
        if (null == umsMember) {
            umsMember = new UmsMember();
        }
        BeanUtil.copyProperties(user, umsMember, true);
        if (null == umsMember.getId()) {
            umsMemberRepository.insert(umsMember);
        } else {
            umsMemberRepository.update(umsMember);
        }
    }

    public int deleteByUser(List<Long> ids) {
        return umsMemberRepository.deleteByProperties("Q_userId_L_IN", ids);
    }
}
